from flask import (
    url_for,
    request,
    jsonify,
    session,
)
import time
from datetime import datetime, timedelta
from sqlalchemy.sql import func, extract
from .forms import LoginForm
from application import db
from .models import User, Order,Setting
from apps.front.models import FrontUser,Distribution,TransferHistory
from flask_restful import Resource
from flask_restful import marshal_with, marshal
from .fields import *
from .inputs import *
from utils.Base import Page


class Login(Resource):

    def post(self):
        inputs = LOGIN_VALID.parse_args(req=request)
        if inputs:
            username = inputs['username']
            password = inputs['password']
            user = db.session.query(User).filter(
                User.login_name == username).first()
            if not user:
                return {
                    'code': 403,
                    'message': '找不到用户'
                }

            if user.status != 1:
                return {
                    'code': 403,
                    'message': '账号被封禁，请联系管理员'
                }

            elif user.checkPassWord(password):
                return {
                    'code': 200,
                    'token': user.get_jwt_str(),
                    'permission': ['admin']
                }
            else:
                return {
                    'code': 403,
                    'message': '用户名或密码错误'
                }
        else:
            error_message = forms.errors.popitem()
            return {
                'code': 403,
                'message': error_message[1][0]
            }


class FrontUserReSource(Resource):

    def get(self):
        username = request.args.get('username')
        result = db.session.query(FrontUser).filter(
            FrontUser.login_name.like('%%%s%%' % (username))).all()

        P = Page(result)

        return marshal({
            'code': 200,
            'msg': '获取成功',
            'data': P.data,
            'page': P.page_info
        }, FrontUseListrFields)

    def put(self):

        password = request.json.get('password')
        username = request.json.get('username')
        user = FrontUser(login_name=username, login_pwd=password)

        db.session.add(user)
        db.session.commit()

        return marshal({
            'code': 200,
            'msg': '新建成功',
            'data': user
        }, FrontUseOnerFields)

    def delete(self):
        id = request.args.get("id")
        user = db.session.query(FrontUser).filter(FrontUser.id == id).first()
        if user:
            db.session.delete(user)
            db.session.commit()
        return {
            'code': 200,
            'msg': '删除成功'
        }

    def post(self):
        id = request.json.get('id')
        nick_name = request.json.get('nick_name')
        is_distribution = request.json.get('is_distribution')
        user = db.session.query(FrontUser).filter(FrontUser.id == id).first()

        if user:
            user.is_distribution = is_distribution
            user.nick_name = nick_name
            db.session.commit()
        return {
            'code': 200,
            'msg': '修改成功'
        }


class Charts(Resource):

    def get(self):
        today = time.strftime('%Y-%m-%d')
        startmonth = time.strftime('%Y-%%s-%%s 0:0:0')
        endmonth = time.strftime('%Y-%%s-%%s 23:59:59')
        totalSaleCount = db.session.query(
            func.sum(Order.pay_number),func.count(Order.id)).filter(Order.is_pay == True).first()

        mine = db.session.query(
            func.sum(Order.pay_number)).filter(Order.is_distribution == False,Order.is_pay == True).first()
        distribution =  db.session.query(
            func.sum(Order.pay_number)).filter(Order.is_distribution == True,Order.is_pay == True).first()
        day = db.session.query(func.sum(Order.pay_number)).filter(Order.is_pay == True)\
            .filter(Order.update_time.between(today+' 0:0:0', today+' 23:59:59')).first()

        distribution_sale = db.session.query(func.sum(Distribution.pay_number),func.count(Distribution.pay_number)).filter(Distribution.is_pay == True).first()
        totalOrderNumber = db.session.query(func.count(Order.id)).first()
        transfer_total = db.session.query(func.sum(TransferHistory.transfer_number)).filter(TransferHistory.is_transfer == True).first()
        salesData = []

        for i in range(1,13):
            if i in [1,3,5,7,8,10,12]:
                total = db.session.query(func.sum(Order.pay_number)).filter(Order.is_pay == True)\
                .filter(Order.update_time.between(startmonth%(i,1), endmonth%(i,31))).first()
            else:
                total = db.session.query(func.sum(Order.pay_number)).filter(Order.is_pay == True)\
                .filter(Order.update_time.between(startmonth%(i,1), endmonth%(i,30))).first()
            salesData.append({'x':'%s月'%(i),'y':int(total[0]) if total[0] else 0})

        return {
            'code': 200,
            'msg': '获取成功',
            'data': {
                'totalSaleCount': {
                    'total': str(totalSaleCount[0]),
                    'day': str(day[0] if day[0] else 0),
                    'payOrderCount':totalSaleCount[1],
                    'distributionSale':str(distribution_sale[0] if distribution_sale[0] else 0),
                    'distributionSaleNumber':str(distribution_sale[1] if distribution_sale[1] else 0),
                    'transfer_total':str(transfer_total[0] if transfer_total[0] else 0),
                    'conversion':totalSaleCount[1] / totalOrderNumber[0]
                },
                'salesData':salesData,
                'salesTypeData':[
                    {'x':'网站售出','y':float(mine[0]) if mine[0] else 0},
                    {'x':'分销商','y':float(distribution[0]) if distribution[0] else 0},
                ]
            }
        }



class SettingResource(Resource):

    def get(self):
        setting = db.session.query(Setting).order_by('-id').first()

        return marshal({
            'code':200,
            'msg':'获取成功',
            'data':setting
        },SettingFields)

    def post(self):

        try:
            setting = Setting(**request.json)
            db.session.add(setting)
            db.session.commit()
        except Exception as e:
            return {
                'code':400,
                'msg':'数据异常'
            }

        return marshal({
            'code':200,
            'msg':'获取成功',
            'data':setting
        },SettingFields)



class TransferReSource(Resource):

    def get(self):
        user = request.args.get('user','')
        result = request.args.get('result')
        if result:
            result = result == 'true'
            result = db.session.query(TransferHistory).join(FrontUser,FrontUser.id == TransferHistory.user_id)\
                .filter(TransferHistory.is_transfer == result).filter(FrontUser.login_name.like('%%%s%%'%(user))).all()
        else:
            result = db.session.query(TransferHistory).join(FrontUser,FrontUser.id == TransferHistory.user_id).filter(FrontUser.login_name.like('%%%s%%'%(user))).all()

        P = Page(result)

        return marshal({
            'code':200,
            'page':P.page_info,
            'data':P.data,
            'msg':'获取成功'
        },TransferHistoryFields)